# -*- coding: utf-8 -*-
#   关于菜单和工具栏命令的工具
# @Time    ： 2025/11/12  01:23
# @Auther  ： 徐良
# File     :  menu_action_item_tool.py
from typing import List, Optional, Dict
from PySide6.QtSql import QSqlQueryModel
from dbService import get_model


def get_menu_mode(action_num: str) -> QSqlQueryModel:
    """获取菜单model

    Args:
        action_num: 动作编号，用于推导菜单层级

    Returns:
        QSqlQueryModel: 菜单模型
    """
    parts = action_num.split(".")
    prefix = ".".join(parts) + "."
    length = len(prefix)
    sql = (f"SELECT e.FNumber, e.FName, e.FId, e.FParentId, e.FLevel, e.FDetail FROM t_menu e "
           f"LEFT JOIN t_menu m ON e.FParentId = m.FId WHERE SUBSTR(e.FNumber, 1, {length}) = "
           f"'{prefix}' ORDER BY e.FNumber")
    return get_model(sql)


def get_action_model(action_prefix: str) -> QSqlQueryModel:
    """获取工具栏动作列表

    Args:
        action_prefix: 动作编号前缀（如'S01.001'）

    Returns:
        QSqlQueryModel: 包含动作信息的模型
    """
    sql = f"""
    SELECT FNumber, FName, FObjectname, FIcon, FTooltip, FEnable, FVisible 
    FROM t_action 
    WHERE FNumber LIKE '{action_prefix}%' 
      AND FObjectname <> 'N' 
      AND FVisible = 1 
    ORDER BY FNumber
    """

    return get_model(sql)


def get_browse_action_model(menu_num: str) -> Optional[QSqlQueryModel]:
    """获取浏览界面工具栏动作列表

    Args:
        menu_num: 菜单编号

    Returns:
        List[str]: 动作名称列表
    """
    # sql = f"SELECT FMenusAndActions FROM t_masterslave WHERE fnumber='{menu_num}'"
    # model = get_model(sql)
    # if model.rowCount() == 0:
    #     return []
    #
    # try:
    #     actions = eval(model.record(0).value("FMenusAndActions"))
    #     return actions.get("browseAction", "").split(",")
    # except Exception:
    #     return []

    return None


def get_edit_action_model(menu_num: str) -> Optional[QSqlQueryModel]:
    """获取编辑界面工具栏动作列表

    Args:
        menu_num: 菜单编号

    Returns:
        List[str]: 动作名称列表
    """
    # sql = f"SELECT FMenusAndActions FROM t_masterslave WHERE fnumber='{menu_num}'"
    # model = get_model(sql)
    # if model.rowCount() == 0:
    #     return []
    #
    # try:
    #     actions = eval(model.record(0).value("FMenusAndActions"))
    #     return actions.get("editAction", "").split(",")
    # except Exception:
    #     return []
    return None


def get_navigation_config(number: str)-> Dict[str, str]:
    """
    获取导航条目的信息，字段格式
    :param number:
    :return:
    """
    sql = f"select * from t_navigation where FNumber='{number}' and FDetail=1"
    model = get_model(sql)
    rows = model.rowCount()
    ret = {}
    for i in range(0, rows):
        if number == model.record(i).value('fnumber'):
            ret['fname'] = model.record(i).value('fname')
            ret['fpackage'] = model.record(i).value('fpackage')
            ret['fclass'] = model.record(i).value('fclass')
            ret['fpara'] = model.record(i).value('fpara')
            break
    return ret

